import {
  Injectable,
  ConflictException,
  NotFoundException,
  Logger,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import * as bcrypt from 'bcryptjs';

@Injectable()
export class UsersService {
  private readonly logger = new Logger(UsersService.name);

  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  async create(createUserDto: CreateUserDto): Promise<User> {
    const { username, email, password } = createUserDto;

    // 检查用户名或邮箱是否已存在
    const existingUser = await this.usersRepository.findOne({
      where: [{ username }, { email }],
    });

    if (existingUser) {
      this.logger.warn(`创建用户失败: 用户名 ${username} 或邮箱 ${email} 已存在`);
      throw new ConflictException('用户名或邮箱已存在');
    }

    // 创建新用户
    const hashedPassword = await bcrypt.hash(password, 10);
    this.logger.log(`创建新用户: ${username}`);
    
    const user = this.usersRepository.create({
      username,
      email,
      password: hashedPassword,
    });

    return this.usersRepository.save(user);
  }

  async findByUsername(username: string): Promise<User> {
    this.logger.log(`查找用户: ${username}`);
    const user = await this.usersRepository.findOne({ where: { username } });
    
    if (!user) {
      this.logger.warn(`用户 ${username} 不存在`);
      throw new NotFoundException(`用户 ${username} 不存在`);
    }
    
    this.logger.log(`找到用户: ${username}`);
    return user;
  }

  async findById(id: number): Promise<User> {
    this.logger.log(`通过ID查找用户: ${id}`);
    const user = await this.usersRepository.findOne({ where: { id } });
    
    if (!user) {
      this.logger.warn(`ID为 ${id} 的用户不存在`);
      throw new NotFoundException(`ID为 ${id} 的用户不存在`);
    }
    
    this.logger.log(`找到ID为 ${id} 的用户`);
    return user;
  }
}
